const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const { userAuth } = require('../middleware/userAuth');
const { query } = require('../config/db');
const ApiResponse = require('../utils/response');

/**
 * @route   POST /api/users/register
 * @desc    用户注册
 * @access  Public
 */
router.post('/register', userController.register);

/**
 * @route   POST /api/users/login
 * @desc    用户登录
 * @access  Public
 */
router.post('/login', userController.login);

/**
 * @route   GET /api/users/profile
 * @desc    获取当前用户信息
 * @access  Private
 */
router.get('/profile', userAuth, userController.getCurrentUser);

/**
 * @route   PUT /api/users/profile
 * @desc    更新用户信息
 * @access  Private
 */
router.put('/profile', userAuth, userController.updateProfile);

/**
 * @route   PUT /api/users/password
 * @desc    修改密码
 * @access  Private
 */
router.put('/password', userAuth, userController.changePassword);

/**
 * @route   GET /api/users/areas
 * @desc    获取区域列表（支持按级别和父ID查询）
 * @access  Public
 * @query   level - 级别(1-省, 2-市, 3-县/区)
 * @query   parent_id - 父级区域ID
 */
router.get('/areas', async (req, res, next) => {
  try {
    const { level, parent_id } = req.query;
    
    let sql = 'SELECT id, name, level, parent_id, code FROM areas WHERE 1=1';
    const params = [];

    if (level) {
      sql += ' AND level = ?';
      params.push(parseInt(level));
    }

    if (parent_id) {
      sql += ' AND parent_id = ?';
      params.push(parseInt(parent_id));
    } else if (!level) {
      // 如果没有指定parent_id且没有指定level，默认返回省级
      sql += ' AND level = 1';
    }

    sql += ' ORDER BY code, name';

    const areas = await query(sql, params);
    
    return ApiResponse.success(res, areas);

  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/users/areas/:id
 * @desc    获取指定区域的详细信息（包括父级信息）
 * @access  Public
 */
router.get('/areas/:id', async (req, res, next) => {
  try {
    const { id } = req.params;

    const sql = `
      SELECT a1.id, a1.name, a1.level, a1.parent_id, a1.code,
             a2.name as parent_name,
             a3.name as grandparent_name
      FROM areas a1
      LEFT JOIN areas a2 ON a1.parent_id = a2.id
      LEFT JOIN areas a3 ON a2.parent_id = a3.id
      WHERE a1.id = ?
    `;

    const results = await query(sql, [id]);
    
    if (results.length === 0) {
      return ApiResponse.notFound(res, '区域不存在');
    }

    return ApiResponse.success(res, results[0]);

  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/users/areas/tree
 * @desc    获取区域树形结构（省-市-县）
 * @access  Public
 * @query   province_id - 指定省份ID，只返回该省份的树形结构
 */
router.get('/areas-tree', async (req, res, next) => {
  try {
    const { province_id } = req.query;
    
    // 获取省级数据
    let provinceSql = 'SELECT id, name, code FROM areas WHERE level = 1';
    const provinceParams = [];
    
    if (province_id) {
      provinceSql += ' AND id = ?';
      provinceParams.push(province_id);
    }
    
    provinceSql += ' ORDER BY code';
    
    const provinces = await query(provinceSql, provinceParams);
    
    // 为每个省获取市级数据
    for (let province of provinces) {
      const cities = await query(
        'SELECT id, name, code FROM areas WHERE level = 2 AND parent_id = ? ORDER BY code',
        [province.id]
      );
      
      // 为每个市获取县/区级数据
      for (let city of cities) {
        const counties = await query(
          'SELECT id, name, code FROM areas WHERE level = 3 AND parent_id = ? ORDER BY code',
          [city.id]
        );
        city.children = counties;
      }
      
      province.children = cities;
    }
    
    return ApiResponse.success(res, province_id ? provinces[0] : provinces);

  } catch (error) {
    next(error);
  }
});

module.exports = router;

